import { customRef } from "vue";

export function debounce(fn, delay = 1000) {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
}
/* 自定义ref实现防抖 */
export function debounceRef(value, delay = 1000) {
  let timer = null;
  return customRef((track, trigger) => ({
    get() {
      // 依赖收集
      track();
      console.log("get", value);
      return value;
    },
    set(val) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        value = val;
        console.log("set", value);
        trigger();
      }, delay);
    },
  }));
}
